<?php
abstract class BaseViewControl extends BaseControl
{
    protected $view;

    public function BaseViewControl($name)
    {
        BaseConfig::GetInstance()->AddCss('controls/resizer, controls/CalendarDateSelect');
        BaseConfig::GetInstance()->AddSharedJs('controls/DropdownControl, controls/resizer, controls/CalendarDateSelect, controls/DaterangeControl');
        GridConfig::GetInstance()->AddSharedJs('GridControl, GridSelectControl');
        BaseConfig::GetInstance()->AddSharedJs('controls/tooltip');
        parent::__construct($name);
        $this->LoadView();
    }

    protected function LoadView()
    {}

    protected function GetEditBoxes()
    {
        $model_name = $this->view->GetModelName();
        $boxes = array();
        foreach($this->view->GetEnabledFields() as $field_name => $field)
        {
            $box = null;
            if ($field->editable)
            {
                $box = $this->GetEditBox($field, $field_name);
            }
            $boxes["editbox-$field_name"] = $box;
        }
        return $boxes;
    }

    protected function GetEditBox($field)
    {
        $config = VmConfig::GetInstance();
        $model_name = $this->view->GetModelName();
        switch ($field->formatType)
        {
            case $config->FIELDTYPE_SELECT:
            case $config->FIELDTYPE_TREE_SELECT:
                $options = SelectControl::GetOptions($field->selectList, null, null);
                $box = "<select class='box elastic' name='{$model_name}[#id][{$field->name}]'>$options</select>";
                break;
            case $config->FIELDTYPE_CHECKBOX:
                $box = "<input class='box' name='{$model_name}[#id][{$field->name}]' type='checkbox' #checked value='#v'/>";
                break;
            case $config->FIELDTYPE_DATEPICKER:
                $box = "<div class='boxwrapper'><input class='box elastic' name='{$model_name}[#id][{$field->name}]' value='#v' id='{$field->name}#id' type='datetime'/></div>";
                break;
            case $config->FIELDTYPE_TEXTAREA:
                $box = "<textarea class='box elastic' name='{$model_name}[#id][{$field->name}]'>#v</textarea>";
                break;
            case $config->FIELDTYPE_HTMLEDITOR:
                BaseConfig::GetInstance()->AddSharedJsNoPack('tiny_mce/tiny_mce');
                $box = "<textarea class='box elastic htmleditor' name='{$model_name}[#id][{$field->name}]'>#v</textarea>";
                break;
            case $config->FIELDTYPE_GRID_SELECT:
                $box = "<div class='boxwrapper nomargin'><input class='box elastic gridselect_ready' name='{$model_name}[#id][{$field->name}]' drop='{$this->name}_{$field->name}' value='#v' display='#f' /></div>";
                break;
            default:
                $box = "<div class='boxwrapper'><input class='box elastic' name='{$model_name}[#id][{$field->name}]' value='#v'/></div>";
                break;
        }
        return $box;
    }

    public function GetFieldFormated($value, $field, $row, $level = null)
    {
        if ($field->cropLength)
            $value = String::Crop($value, $field->cropLength);

        return $this->GetFormatedCell($value, $field, $row, $level);
    }

    protected function GetFormatedCell($value, $field, $row, $level = null)
    {
        $config = VmConfig::GetInstance();
        $floatleft = false;
        switch ($field->formatType)
        {
            case $config->FIELDTYPE_SELECT:
                $value = isset($field->selectList[$value]) ? $field->selectList[$value] : null;
                $floatleft = true;
                break;
            case $config->FIELDTYPE_IMAGE:
                $value = $this->GetImage($value);
                break;
            case $config->FIELDTYPE_CHECKBOX:
                $value = $this->GetCheckboxIcon($value);
                break;
            case $config->FIELDTYPE_GRID_SELECT:
                $value = $value ? $this->GetSelectedDisplay($field, $value) : '&nbsp;';
                $value = "<span class='displayvalue'>$value</span>";
                break;
            case $config->FIELDTYPE_CURRENCY:
                $value = AppConfig::GetInstance()->GetCurrencyModel()->FormatDefaultPrice($value);
                break;
            case $config->FIELDTYPE_PASSWORD:
                $value = '*****';
                break;
            case $config->FIELDTYPE_TEXTBOX:
                if ($field->foreignKey && $field->refField)
                {
                    $value = $value ? $this->GetSelectedDisplay($field, $value) : '&nbsp;';
                    $value = "<span class='displayvalue'>$value</span>";
                }
                break;
            case $config->FIELDTYPE_HTML:
                $value = htmlentities($value);
                break;
            case $config->FIELDTYPE_TEXTAREA:
                $value = nl2br($value);
                break;
        }
        if ($field->drilldownUrl)
            $value = $this->GetDrilldownUrl($field->drilldownUrl, $row, $value);
        if ($floatleft)
            $value = "<div class='floatleft'>$value</div>";
        return $value;
    }

    protected function GetImage($value)
    {
        if ($value)
        {
            $value = Photo::GetInstance()->GetThumbUrl($value);
            return "<img class='thumbimg' src='$value' />";
        }
    }

    public function GetNowrap($value, $field)
    {
        return $field->IsString() && strlen($value)>100 ? null : 'nowrap="nowrap"';
    }

    public function GetKey($row)
    {
        $pk = $this->view->GetModelPrimaryKey();
        $pks = explode('::', $pk);
        if (count($pks) == 1)
            return $pk ? Set::Get($row, $pk) : null;
        else
        {
            foreach ($pks as $p)
            {
                $keys[$p] = Set::Get($row, $p);
            }
            return implode('::', $keys);
        }
    }

    protected function GetCssDataType($field)
    {
        if ($field->formatType == VmConfig::GetInstance()->FIELDTYPE_IMAGE) return 'center';
        return $field->IsNumeric() ? 'number' : null;
    }

    protected function GetEditable($field)
    {
        return $this->view->allowEdit && $field->editable ? 'editable' : null;
    }

    protected function GetNotFormated($field)
    {
        return $field->IsHtmlEditor() ? 'notformated' : null;
    }

    protected function GetSelectedDisplay($field, $id)
    {
        if (is_null($id)) return null;

        $field_name = $field->name;
        if (!isset($this->displayValues[$field_name][$id]))
        {
            $ref_model = Model::GetInstanceByName($field->foreignKey->table);
            $this->displayValues[$field_name][$id] = $ref_model->FindScalarById($id, $field->refField);
        }
        return $this->displayValues[$field_name][$id];
    }

    public function FormatColumn($field)
    {
        $item = (array) $field;
        $item['datatype'] = $this->GetCssDataType($field);
        $item['editable'] = $this->GetEditable($field);
        $item['notformated'] = $this->GetNotFormated($field);
        return $item;
    }

    protected function GetCheckboxIcon($value)
    {
        if ($value)
        {
            $src = GridConfig::GetInstance()->URL_IMG.'/check.png';
            return "<img src='$src' />";
        }
    }

    protected function GetDrilldownUrl($url, $row, $label)
    {
        preg_match_all('/\[\:([^:\]]+)\:\]/', $url, $match);
        if (!empty($match) && !empty($match[0]) && !empty($match[1]))
        {
            $match = array_combine($match[0], $match[1]);
            foreach ($match as $key=>$value)
            {
                if (isset($row[$value]))
                    $url = str_replace($key, $row[$value], $url);
            }
        }

        $attribute_prefix = 'attribute:';
        $action_prefix = 'action:';

        if (String::Beginwith($attribute_prefix, $url))
        {
            $attribute = String::CropBegin($attribute_prefix, $url);
            return "<span $attribute>$label</span>";
        }
        else if (String::Beginwith($action_prefix, $url))
        {
            $action = String::CropBegin($action_prefix, $url);
            return "<span $action class='action_item'>$label</span>";
        }
        else
            return "<a href='$url'>$label</a>";
    }

    public function FilterBy($field, $value)
    {
        $_REQUEST['filter'][$field] = $value;
    }

    protected function IsEnabled($field_name)
    {
        return $this->view->GetField($field_name)->enabled;
    }
}
?>
